package com.zlx.mall.basic.common.holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * @author qingke
 **/
@Component
public class ApplicationPropertiesHolder {

    public static final Set<String> ACTIVE_PRODUCT_SET;
    public static final Set<String> ACTIVE_TEST_SET;
    public static final Set<String> ACTIVE_DEVELOP_SET;

    static {
        ACTIVE_PRODUCT_SET = new HashSet<>();
        ACTIVE_PRODUCT_SET.add("prod");
        ACTIVE_PRODUCT_SET.add("product");
        ACTIVE_PRODUCT_SET.add("live");

        ACTIVE_TEST_SET = new HashSet<>();
        ACTIVE_TEST_SET.add("test");
        ACTIVE_TEST_SET.add("sandbox");

        ACTIVE_DEVELOP_SET = new HashSet<>();
        ACTIVE_DEVELOP_SET.add("dev");
        ACTIVE_DEVELOP_SET.add("develop");
    }

    private static Environment ENVIRONMENT;

    /** Active Env */
    public static String ACTIVE;

    /** Application Name */
    public static String APPLICATION_NAME;

    @Autowired
    protected void setEnvironment(Environment environment) {
        ApplicationPropertiesHolder.ENVIRONMENT = environment;
    }

    @Value("${spring.profiles.active:default}")
    public void setActive(String active) {
        ApplicationPropertiesHolder.ACTIVE = active;
    }

    @Value("${spring.application.name:app}")
    public void setApplicationName(String applicationName) {
        ApplicationPropertiesHolder.APPLICATION_NAME = applicationName;
    }

    public static boolean isDevelopActive() {
        return ACTIVE_DEVELOP_SET.contains(ACTIVE);
    }

    public static boolean isTestActive() {
        return ACTIVE_TEST_SET.contains(ACTIVE);
    }

    public static boolean isProductActive() {
        return ACTIVE_PRODUCT_SET.contains(ACTIVE);
    }

    public static boolean containsProperty(String key) {
        return StringUtils.hasText(key) && ENVIRONMENT.containsProperty(key);
    }

    public static String getProperty(String key) {
        return StringUtils.hasText(key) ? ENVIRONMENT.getProperty(key) : null;
    }

    public static String getProperty(String key, String defaultValue) {
        return ENVIRONMENT.getProperty(key, defaultValue);
    }

    public static Integer getIntProperty(String key, int defaultValue) {
        return ENVIRONMENT.getProperty(key, Integer.TYPE, defaultValue);
    }

    public static <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
        return ENVIRONMENT.getProperty(key, targetType, defaultValue);
    }
}
